package com.example.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.example.common.constant.ProductConstant;
import com.example.common.to.SkuReductionTo;
import com.example.common.to.SpuBoundTo;
import com.example.common.to.es.SkuEsModel;
import com.example.common.to.hasStockVo;
import com.example.common.utils.R;
import com.example.gulimall.product.entity.*;
import com.example.gulimall.product.feign.CouponFeignService;
import com.example.gulimall.product.feign.SearchFeignService;
import com.example.gulimall.product.feign.WareFeignService;
import com.example.gulimall.product.service.*;
import com.example.gulimall.product.vo.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.utils.PageUtils;
import com.example.common.utils.Query;

import com.example.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    SpuInfoDescService descService;

    @Autowired
    SpuImagesService spuImagesService;

    @Autowired
    SkuImagesService skuImagesService;

    @Autowired
    AttrService attrService;

    @Autowired
    ProductAttrValueService productAttrValueService;

    @Autowired
    SkuInfoService skuInfoService;

    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    CouponFeignService couponFeignService;

    @Autowired
    BrandService brandService;

    @Autowired
    CategoryService categoryService;

    @Autowired
    WareFeignService wareFeignService;

    @Autowired
    SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo spuInfo) {

        // 1.保存基本信息 spu_info

        SpuInfoEntity infoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuInfo,infoEntity);
        infoEntity.setCreateTime(new Date());
        infoEntity.setUpdateTime(new Date());
        // 实体插入数据库后 自动生成的id会回写
        this.saveBaseSpuInfo(infoEntity);

        // 2.保存描述图片
        List<String> decript = spuInfo.getDecript();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setDecript(String.join(",",decript));
        spuInfoDescEntity.setSpuId(infoEntity.getId());
        descService.saveSpuInfoDesc(spuInfoDescEntity);


        // 3.保存图片集 spu_imgs
        List<String> images = spuInfo.getImages();
        spuImagesService.saveImages(images, infoEntity.getId());


        // 4.保存规格参数
        List<BaseAttrs> baseAttrs = spuInfo.getBaseAttrs();
        List<ProductAttrValueEntity> collect = baseAttrs.stream().map(attr -> {
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            productAttrValueEntity.setAttrId(attr.getAttrId());

            AttrEntity id = attrService.getById(attr.getAttrId());
            productAttrValueEntity.setAttrName(id.getAttrName());

            productAttrValueEntity.setAttrValue(attr.getAttrValues());
            productAttrValueEntity.setQuickShow(attr.getShowDesc());
            productAttrValueEntity.setSpuId(infoEntity.getId());
            return productAttrValueEntity;
        }).collect(Collectors.toList());

        productAttrValueService.saveProductAttr(collect);


        // 保存spu积分信息
        Bounds bounds = spuInfo.getBounds();
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtils.copyProperties(bounds,spuBoundTo);
        spuBoundTo.setSpuId(infoEntity.getId());
        R r1 = couponFeignService.saveSpuBounds(spuBoundTo);
        if(r1.getCode() != 0){
            log.error("spu积分保存失败");
        }


        // 5.保存spu相关的sku信息
        List<Skus> skus = spuInfo.getSkus();
        if(skus != null && skus.size() > 0){
            skus.forEach(item->{
                String defaultimg = "";
                for(Images image : item.getImages()){
                    if(image.getDefaultImg() == 1)
                        defaultimg = image.getImgUrl();
                }

                SkuInfoEntity entity = new SkuInfoEntity();
                BeanUtils.copyProperties(item,entity);
                entity.setBrandId(infoEntity.getBrandId());
                entity.setCatalogId(infoEntity.getCatalogId());
                entity.setSaleCount(0L);
                entity.setSpuId(infoEntity.getId());
                entity.setSkuDefaultImg(defaultimg);
                // 5.1 基本信息
                skuInfoService.saveSkuInfo(entity);

                // 5.2 sku图片信息
                Long skuId = entity.getSkuId();

                List<SkuImagesEntity> imagesEntities = item.getImages().stream().map(img -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    return skuImagesEntity;
                }).filter(imgs->{
                    return !StringUtils.isEmpty(imgs.getImgUrl());
                }).collect(Collectors.toList());
                skuImagesService.saveBatch(imagesEntities);

                // 5.3 sku的销售属性信息
                List<Attr> attr = item.getAttr();
                List<SkuSaleAttrValueEntity> attrValueEntities = attr.stream().map(a -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(a, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuId);
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(attrValueEntities);

                // 5.4 sku的优惠满减信息
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(item,skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                if(skuReductionTo.getFullCount() > 0 || skuReductionTo.getFullPrice().compareTo(new BigDecimal("0")) == 1){
                    R r = couponFeignService.saveSkuReduction(skuReductionTo);
                    if(r.getCode() != 0){
                        log.error("远程保存sku优惠信息失败");
                    }
                }


            });
        }







    }

    @Override
    public void saveBaseSpuInfo(SpuInfoEntity infoEntity) {
        this.baseMapper.insert(infoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {

        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();

        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)){
            wrapper.and((w)->{
               w.eq("id",key).or().like("spu_name",key);
            });
        }

        String status = (String) params.get("status");
        if(!StringUtils.isEmpty(status)){
            wrapper.eq("publish_status",status);
        }

        String brandId = (String) params.get("brandId");
        if(!StringUtils.isEmpty(brandId)){
            wrapper.eq("brand_Id",brandId);
        }

        String catelogId = (String) params.get("catalogId");
        if(!StringUtils.isEmpty(catelogId)){
            wrapper.eq("catalog_id",catelogId);
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void up(Long spuId) {

        // 1.组装需要的数据
        List<SkuInfoEntity> skus = skuInfoService.getSkuInfoBySpuId(spuId);

        // 4. 检测Attr属性
        List<ProductAttrValueEntity> entities = productAttrValueService.baseAttrlistforspu(spuId);
        List<Long> longs = entities.stream().map(ProductAttrValueEntity::getAttrId).collect(Collectors.toList());

        List<Long> searchAttrIds = attrService.selectSearchAttrIds(longs);
        Set<Long> idSet = new HashSet<>(searchAttrIds);

        List<SkuEsModel.Attr> attrList = entities.stream().filter(attr -> idSet.contains(attr.getAttrId())).map(item -> {
            SkuEsModel.Attr s1 = new SkuEsModel.Attr();
            BeanUtils.copyProperties(item, s1);
            return s1;
        }).collect(Collectors.toList());

        // System.out.println("SkuEsmodel中的Attr是"+attrList.toString());

        // 获取ids
        Map<Long, hasStockVo> hasStock = null;
        List<Long> skuIds = skus.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
        try {
            R r = wareFeignService.hasStock(skuIds);
            // List<hasStockVo> vos = (List<hasStockVo>) r.get("data");
            // System.out.println(vos.toString());
            TypeReference<List<hasStockVo>> typeReference = new TypeReference<List<hasStockVo>>() {};
            hasStock = r.getData(typeReference).stream().collect(Collectors.toMap(hasStockVo::getSkuId, item -> item));
        }catch (Exception e){
            System.out.println("这边报错啦！！");
            System.out.println(e);
            log.error("上架方法中的查询服务失败");
        }



        // 2.封装sku的信息
        //System.out.println("此时的结果是"+hasStock.toString());
        Map<Long, hasStockVo> finalHasStock = hasStock;
        List<SkuEsModel> collect = skus.stream().map(item -> {
            SkuEsModel model = new SkuEsModel();
            BeanUtils.copyProperties(item, model);
            model.setSkuPrice(item.getPrice());
            model.setSkuImg(item.getSkuDefaultImg());

            // 是否有库存
            if(finalHasStock != null)
            model.setHasStock(finalHasStock.get(item.getSkuId()).getHasStock());
            else
            model.setHasStock(true);
            // 热度评分
            model.setHotScore(0L);

            // 查询基础信息
            BrandEntity byId = brandService.getById(model.getBrandId());
            model.setBrandImg(byId.getLogo());
            model.setBrandName(byId.getName());

            CategoryEntity byId1 = categoryService.getById(model.getCatalogId());
            model.setCatalogName(byId1.getName());

            // 设置检索
            model.setAttrs(attrList);
            // System.out.println("==========="+model+"===============");
            return model;
        }).collect(Collectors.toList());

        // System.out.println("========到这里也没问题！！！！=======");

        R r = searchFeignService.productStatusUp(collect);
        if(r.getCode()==0){
            baseMapper.updateSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
        }else{
            //失败
            //todo 接口幂等性：重试机制

            /**Feign调用机制
             1.构造请求数据,将对象转换为json
             2.发送请求执行
             3.执行请求会有重试机制
             *
             */
        }
    }

    @Override
    public SpuInfoEntity getSpuInfoBySkuId(Long skuId) {
        SkuInfoEntity id = skuInfoService.getById(skuId);
        return getById(id.getSpuId());
    }

}